package 多线程01_启动线程;

/**
 * @ClassName: 多线程01_启动线程.Hero
 * @Author: AllenSun
 * @Date: 2022/3/18 上午12:45
 */
public class Hero {
    public String name;
    public float hp;
    public int damage;

    public Hero(String name) {
        this.name = name;
    }

    public Hero(String name, float hp) {
        this.name = name;
        this.hp = hp;
    }

    public Hero(String name, float hp, int damage) {
        this.name = name;
        this.hp = hp;
        this.damage = damage;
    }

    //回血
    public void recover(){
        hp=hp+1;
    }

    //掉血
    public void hurt(){
        hp=hp-1;
    }

    //回血
    public synchronized void recover_syn(){
        hp=hp+1;
    }

    //掉血
    public synchronized void hurt_syn(){
        hp=hp-1;
    }

    public synchronized void recover_notify() {
        hp = hp + 1;
        System.out.printf("%s 回血1点,增加血后，%s的血量是%.0f%n", name, name, hp);
        // 通知那些等待在this对象上的线程，可以醒过来了，如第20行，等待着的减血线程，苏醒过来
        this.notify();
    }

    public synchronized void hurt_wait() {
        if (hp == 1) {
            try {
                // 让占有this的减血线程，暂时释放对this的占有，并等待
                //wait方法和notify方法，并不是Thread线程上的方法，它们是Object上的方法。
                this.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        hp = hp - 1;
        System.out.printf("%s 减血1点,减少血后，%s的血量是%.0f%n", name, name, hp);
    }


    public void attactHero(Hero h) {
        /*try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/

        h.hp-=damage;
        System.out.format("%s 正在攻击 %s，%s 的血变成 %.0f%n",name,h.name,h.name,h.hp);

        if(h.isDead()){
            System.out.println(h.name+"死了");
        }
    }

    public boolean isDead() {
        return 0>hp?true:false;
    }
}
